package com.etc.controller;

import com.etc.entity.User;
import com.etc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
public class UserController {
    @Autowired
    private UserService userService;

    //根据cookie的名字，获取cookie的值
    public static String getCookieValue(String cname,HttpServletRequest request){
        String res = "";
        Cookie cc[] = request.getCookies();
        if(cc != null && cc.length != 0){
            for (Cookie c:cc) {
                if(c.getName().equals(cname)){
                    res = c.getValue();
                    break;
                }
            }
        }
        return res;
    }

    @RequestMapping("/")
    public ModelAndView index(){
        ModelAndView mv = new ModelAndView("login");
        return mv;
    }

    @RequestMapping("/userlogin")
    public ModelAndView login(String uname, String password,
                              @RequestParam(value = "age",required = false,defaultValue = "") String agestr,
                              HttpSession session, HttpServletResponse response){
        ModelAndView mv = new ModelAndView("sysindex");
        User user = userService.query(uname,password);
        if(user != null){
            session.setAttribute("user",user);
            int age = 0;//cookie的时长
            //设置cookie
            if(agestr != null && !"".equals(agestr)) {
                age = Integer.valueOf(agestr)*3600*24;
                //构造cookie
                Cookie cuname = new Cookie("uname",uname);
                Cookie cpassword = new Cookie("password",password);
                cuname.setMaxAge(age);
                cpassword.setMaxAge(age);
                //把cookie设置到响应中
                response.addCookie(cuname);
                response.addCookie(cpassword);
            }
        }else{
            mv.setViewName("login");
            mv.addObject("msg","用户名或密码错误");
        }
        return mv;
    }

    @RequestMapping("/userlogout")
    public ModelAndView userlogout(HttpSession session){
        ModelAndView mv = new ModelAndView("login");
        session.invalidate();
        return mv;
    }
}
